package com.hcc.security.service.serviceImpl;

import com.hcc.security.mapper.PermissionMapper;
import java.util.Collection;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

/**
 * @Author: HC
 * @Date: 2019/4/28 10:46
 * @Version 1.0
 */
@Service
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

  @Autowired
  private PermissionMapper permissionMapper;

  /**
   * 资源权限
   */
  private volatile HashMap<String, Collection<ConfigAttribute>> urlPermMap = null;

  /**
   * 初始化
   */
  @PostConstruct
  public void init() {
    loadResourceDefine();
  }

  /**
   * 初始化
   */
  public void loadResourceDefine() {
    urlPermMap = new HashMap<>();
    //TODO 初始化资源权限信息

  }

  /**
   *
   * @param object
   * @return
   * @throws IllegalArgumentException
   */
  @Override
  public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
    FilterInvocation fi = (FilterInvocation) object;
    String url = fi.getRequestUrl();
    // 资源权限为空，初始化资源
    if (null == urlPermMap) {
      synchronized (SecurityMetadataSource.class) {
        if (null == urlPermMap) {
          loadResourceDefine();
        }
      }
    }
    return urlPermMap.get(url);
  }

  @Override
  public Collection<ConfigAttribute> getAllConfigAttributes() {
    return null;
  }

  /**
   *
   * @param clazz
   * @return
   */
  @Override
  public boolean supports(Class<?> clazz) {
    return FilterInvocation.class.isAssignableFrom(clazz);
  }
}
